package cn.com.tbshuda.shell.shell.server;

/**
 * @author: wsd
 * @date: 2021/6/17 9:18
 */

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SCPOutputStream;
import ch.ethz.ssh2.Session;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.concurrent.CountDownLatch;

/**
 * SshFile
 *
 * @author hackyo
 * @date 2020/9/1
 */
public class SshFile {

    private static final String[] HOSTS = {
            "47.93.248.77"
    };
    private static final String USERNAME = "root";
    private static final String[] PASSWORDS = {"Shuda1112"};
    private static final CountDownLatch LATCH = new CountDownLatch(HOSTS.length);

    public static void main(String[] args) {
        System.out.println("程序运行");
        System.out.println();

        //传输文件
        File localFile = new File("D:\\ssq.html");
        String remoteDir = "/root/";
        for (String host : HOSTS) {
            ScpThread scpThread = new ScpThread(host, localFile, remoteDir);
            scpThread.start();
        }

        //执行命令
        String exec = "echo '成功'";
        for (String host : HOSTS) {
            ExecThread execThread = new ExecThread(host, exec);
            execThread.start();
        }

        try {
            LATCH.await();
            System.out.println("程序结束");
        } catch (InterruptedException e) {
            System.out.println("程序错误：" + e.getMessage());
        }
    }

    private static class ExecThread extends Thread {
        private final String host;
        private final String exec;

        private ExecThread(String host, String exec) {
            this.host = host;
            this.exec = exec;
        }

        @Override
        public void run() {
            StringBuilder re = new StringBuilder("开始连接-" + host + "：");
            Connection conn = new Connection(host);
            try {
                conn.connect();
                boolean isAuthenticated = false;
                for (String password : PASSWORDS) {
                    isAuthenticated = conn.authenticateWithPassword(USERNAME, password);
                    if (isAuthenticated) {
                        break;
                    }
                }
                if (isAuthenticated) {
                    Session session = conn.openSession();
                    session.execCommand(exec);
                    InputStream stdoutIn = session.getStdout();
                    re.append("执行输出：");
                    re.append(IOUtils.toString(stdoutIn));
                    re.append("；执行成功；");
                    stdoutIn.close();
                    session.close();
                } else {
                    re.append("无法登录；");
                }
            } catch (Exception e) {
                re.append("执行失败：").append(e.getMessage()).append("；");
            }
            conn.close();
            System.out.println(re.toString());
            System.out.println();
            LATCH.countDown();
        }
    }

    private static class ScpThread extends Thread {
        private final String host;
        private final File localFile;
        private final String remoteDir;

        private ScpThread(String host, File localFile, String remoteDir) {
            this.host = host;
            this.localFile = localFile;
            this.remoteDir = remoteDir;
        }

        @Override
        public void run() {
            StringBuilder re = new StringBuilder("开始连接-" + host + "：");
            Connection conn = new Connection(host);
            try {
                conn.connect();
                boolean isAuthenticated = false;
                for (String password : PASSWORDS) {
                    isAuthenticated = conn.authenticateWithPassword(USERNAME, password);
                    if (isAuthenticated) {
                        break;
                    }
                }
                if (isAuthenticated) {
                    SCPClient scpClient = new SCPClient(conn);
                    SCPOutputStream out = scpClient.put(localFile.getName(), localFile.length(), remoteDir, null);
                    FileInputStream in = new FileInputStream(localFile);
                    IOUtils.copy(in, out);
                    in.close();
                    out.close();
                    re.append("传输成功；");
                } else {
                    re.append("无法登录；");
                }
            } catch (Exception e) {
                re.append("传输失败：").append(e.getMessage()).append("；");
            }
            conn.close();
            System.out.println(re.toString());
            System.out.println();
            LATCH.countDown();
        }
    }

}